<?php

namespace platform;

use app\datacenter\model\Shop;
use think\facade\Log;

/**
 * 云粉吧平台管理(云袋)
 */
class YunDaiPlatform
{
    //默认取号地址
    private string $post_url = "http://api.goluodi.com/wsu/gettask";

    /**
     * 公众号取号接口
     * @param string $uuid
     * @param string $vmid
     * @param string $extra
     * @param string $nickname
     * @param int $sex
     * @return array
     */
    public function queryInterface(string $uuid, string $vmid, string $extra, string $nickname, int $sex): array
    {
        //获取当前设备所在位置Code
        $RegionCode = $this->getRegionCode($vmid);
        $post_data = [
            "userid" => $uuid,
            "deviceid" => $vmid,
            "nickname" => $nickname,
            "sex" => $sex,
            "extra" => $extra,
            'device_area'=>$RegionCode['cityCode']
        ];
        $return_data = $this->post_json(json_encode($post_data));
        Log::write("请求=".json_encode($post_data)."===返回".$return_data,'云袋取号请求');
        return json_decode($return_data, true);
    }

    /**
     * 发起请求
     * @param string $post_data
     * @return bool|string
     */
    private function post_json(string $post_data): bool|string
    {
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $this->post_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8", "Content-Length: " . strlen($post_data)));
        if (!empty($post_data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        return $output;
    }
    /**
     * 通过设备ID获取所在地区编码
     * @param string $mac_id
     * @return array
     */
    private function getRegionCode(string $mac_id): array
    {
        $data['provinceCode'] = '0';
        $data['cityCode'] = '0';
        $data['districtCode'] = '0';
        //获取当前设备的shop信息
        $ShopInfo = Shop::getShopInfo($mac_id);
        if ($ShopInfo) {
            $data['provinceCode'] = $ShopInfo['province_id'];
            $data['cityCode'] = $ShopInfo['city_id'];
            $data['districtCode'] = $ShopInfo['region_id'];
        }
        return $data;
    }


}